// pages/equipmentAdd/equipmentAdd.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
const util = require('../../utils/util');
import Base64 from '../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //厂家id
    factoryId:'',
    //厂家名称
    factoryName:'',
    //厂家选择框
    showFactory:false,
    //厂家设备型号选择框
    showFactoryType:false,
    //厂家设备型号
    equipmentBaseId:'',
    //厂家设备型号显示的名称
    equipmentBaseName:'',
    //经销商id
    dealerId:null,
    //经销商名称
    dealerName:'',
    //经销商选择框
    showDealer:false,
    //客户id
    memberId:null,
    //客户名称
    memberName:'',
    //客户的类型
    memberOfType:null,
    //客户选择框
    showMember:false,
    //客户设备型号选择框
    showUserType:false,
    //客户设备型号
    memberTypeId:'',
    //客户设备型号的名称
    memberTypeName:'',
    memberTypeStr:'',
    //项目id
    projectId:null,
    //项目名称
    projectName:'',
    //项目选择框
    showProject:false,
    //提交按钮是否禁用
    disabled: false,
    //传参来的设备id
    equipmentId:null,
    //编辑时获取的设备信息
    editInfo:{},
    //设备的数据权限
    authDepart:[],
    //登录的客户信息
    userInfo:{},
    //显示上传组件
    showUpload:true,
    //图片
    headImg:'',
    //清洁面积/里程
    workAmount:null,
    //设备品牌
    brand:null,
    //设备品牌显示状态
    brandShow:false,
    //清水箱显示状态
    waterTankShow:false,
    //设备安时数显示状态
    batteryCapacityShow:false,
    //污水箱显示状态
    bilgeTankShow:false,
    //选择清洁单位
    showWorkUnit:false,
    //显示每天达标时间
    standardDurationShow:false,
    //每天达标时间
    standardDuration:3,
    workUnit:'㎡',
    workUnitStr:'㎡/小时',
    workUnitList:[
      {
        text:'㎡/小时',
        workUnit:'㎡'
      },{
        text:'km/小时',
        workUnit:'km'
      }
    ],
    //选择充电方式
    showCharge:false,
    chargeId:2,
    chargeName:'设备外充',
    chargeList:[
      {
        id:1,
        text:'蓄电池直充'
      },{
        id:2,
        text:'设备外充'
      }
    ],
    //是否是修改
    isEdit:false,
    //是否是厂家从订单中绑定设备
    isfactoryBind:false,
    //是否是厂家从新订单中绑定设备
    isfactoryBindNew:false,
    //厂家从订单中绑定设备-传参来的信息
    factoryBind:null,
    //用户权限
    authority:null,
    //设备类型选择数据
    typeList:[],
    //一级分类列表
    typeOne:[],
    //设备类型选择框
    showType:false,
    //选择的设备类型id
    typeIds: [],
    //选择的设备类型名字
    typeNames: '',
    //搜索词
    searchKey:[],
    //保洁供应方id
    cleaningSupplierId:null,
    //保洁供应方名称
    cleaningSupplierName:'',
    //保洁供应方选择框
    showCleaningSupplier:false,
    //搜索保洁供应方输入的值
    valueSearchCleaning:'',
    //保洁供应方项目id
    cleaningSupplierProjectId:null,
    //保洁供应方项目名称
    cleaningSupplierProjectName:'',
    //保洁供应方项目选择框
    showCleaningSupplierProject:false,
    //搜索保洁供应方项目输入的值
    valueSearchCleaningProject:'',
    //搜索客户输入的值
    valueSearchMember:'',
    //搜索项目输入的值
    valueSearchProject:'',
    //所有权
    owner:'',
    //设备修改权
    editer:'',
    //大区id
    regionId:null,
    //大区名称
    regionName:'',
    //大区选择框
    showRegion:false,
    //搜索大区输入的值
    valueSearchRegion:'',
    //避免表单重复提交
    code:null,
    //是否可编辑imei输入框
    isImeiEdit:false,
    //是否显示equipmentNo
    showEquipmentNo: false,
    //是否显示equipmentNo输入框
    showNo:false,
    //是否显示equipmentNo切换
    showNoSwitch:true,
    //业务类型选择框
    showBusinessType:false,
    //业务类型选择数据
    businessTypeList:[],
    //平台id
    myAppId:null,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //appid
		appIdCode: app.globalData.appId,
		//上传路径
		ossUploadUrl: app.globalData.ossUrl
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getUserProfile({
      desc: '为您提供更好的服务',
      success: (res) => {}
    })

    let user=app.globalData.userInfo;
    let equipmentNoSelf=app.globalData.equipmentNoSelf;
    let myAppId=app.globalData.myAppId;

    this.setData({
      userInfo: user,
      authority:app.globalData.authority,
      code:Base64.encode(new Date() + user.userName),
      myAppId:myAppId
    })

    //按平台处理业务类型选择数据
    if(myAppId==7){
      this.setData({
        businessTypeList:[{
          id:1,
          text:'销售'
        },{
          id:6,
          text:'租赁'
        }]
      })
    }else{
      this.setData({
        businessTypeList:[{
          id:5,
          text:'存量改造'
        },{
          id:1,
          text:'销售'
        },{
          id:2,
          text:'租赁-授信'
        },{
          id:3,
          text:'租赁订单-非授信'
        },{
          id:4,
          text:'试机'
        }]
      })
    }

    /*处理是否显示设备编码equipmentNo：
      1角色为 “可以修改设备编码” 的直接可以显示，不受其他限制
      2角色不是 “可以修改设备编码” 的，并且是客户，按配置文件app.js中变量equipmentNoSelf
      3不符合以上两种情况的，可以显示
    */
    if(user.role.indexOf(112)!=-1){
      this.setData({
        showEquipmentNo: true
      })
    }else{
      if(!equipmentNoSelf && user.typeHandle==4){
        this.setData({
          showEquipmentNo: false
        })
      }else{
        this.setData({
          showEquipmentNo: true
        })
      }
    }  

    //判断数登录用户的数据权限是否有100040(龙湖集团)
    let dataAuthArr = user.dataAuthorityOfUser.depart;
    if(dataAuthArr.indexOf(100040)!=-1){
      this.setData({
        waterTankShow:true,
        batteryCapacityShow:true,
        bilgeTankShow:true,
        brandShow:true
      })
    }

    //判断登录用户的数据权限是否有100067（抱朴物业）
    //显示每天达标时长，目前抱朴物业定制
    // if(dataAuthArr.indexOf(100067)!=-1){
    //   this.setData({
    //     standardDurationShow:true
    //   })
    // }

    //equipmentNo可自行填写：配置文件设置了，或是厂家
    if(equipmentNoSelf || user.typeHandle==2){
      this.setData({
        showNoSwitch:false,
        showNo:true
      })
    }

    //获取修改时传过来的设备id
    if(options.equipmentId){
      wx.setNavigationBarTitle({
        title: '修改设备'
      })

      this.setData({
        equipmentId: parseInt(options.equipmentId),
        showUpload:false,
        isEdit:true
      })

      //如果是编辑状态而且登录用户是客户，则无法编辑imei
      //2022-12-6新增，独立经销商的一级部门可以编辑，只有独立小程序加了，蓝涤没加，以后合并时这里要处理
      if(user.departObj[0].type==4){
        this.setData({
          isImeiEdit:true
        })
      }

      //获取设备信息
      this.getEquipmentInfo();
    }

    //厂家从订单中绑定设备-获取参数（原来）
    if(options.factoryBind){
      let obj=JSON.parse(options.factoryBind);
      console.log('厂家订单绑定-传参');
      console.log(obj);

      this.setData({
        factoryBind:obj,
        isfactoryBind:true,
        headImg: obj.pic,
        showUpload:false,
        memberId: obj.memberId,
        dealerId: obj.dealerId,
        memberTypeName:obj.equipmentName,
        //equipmentBaseName:obj.equipmentName,
        projectId:obj.projectId,
      });

      //根据设备型号查询相关信息
      this.findFactoryType();

      //查询项目fid
      if(obj.projectId){
        this.getProjectFid(obj.projectId);
      }
    }

    //厂家从订单中绑定设备-获取参数（新）
    if(options.factoryBindNew){
      let obj=JSON.parse(options.factoryBindNew);
      console.log('厂家新订单绑定-传参');
      console.log(obj);

      //处理清洁面积及单位
      let workAmount = 0;
      let workUnitStr="";
      let workUnit = "";
      if(obj.spu.efficiency != null){
        workAmount = obj.spu.efficiency.value;
        workUnit = obj.spu.efficiency.unit.split("/")[0];
        workUnitStr = obj.spu.efficiency.unit;
      }

      //处理设备类型
      let typeIds=[];
      if(obj.spu && obj.spu.categoryId && obj.spu.categoryId.length){
        typeIds=obj.spu.categoryId;
      }

      //处理设备类型显示名称
      let names=[];
      if(obj.spu && obj.spu.category && obj.spu.category.length){
        let typeNames=obj.spu.category;
        typeNames.forEach(item => {
          names.push(item.name);
        });
      }

      this.setData({
        //写个总的，不用每次加字段了
        factoryBind:obj,
        isfactoryBindNew:true,
        headImg: obj.spu.imgUrl,
        showUpload:false,
        memberId: obj.memberId,
        dealerId: obj.dealerId,
        orderNo:obj.orderNo,
        memberTypeName:obj.equipmentName,
        memberTypeId:obj.spu.id,
        equipmentBaseId:obj.sku.supplierId,
        equipmentBaseName:obj.sku.supplierType,
        projectId:obj.projectId,
        workAmount:workAmount,
        workUnit:workUnit,
        workUnitStr:workUnitStr,
        cleaningSupplierId:obj.cleaningSupplierId,
        cleaningSupplierProjectId:obj.cleaningSupplierProjectId,
        editerIds:obj.editerIds,
        ownerIds:obj.ownerIds,
        cleaningSupplierName:obj.cleaningSupplierName,
        cleaningSupplierProjectName:obj.cleaningSupplierProjectName,
        businessType:obj.businessType,
        typeIds:typeIds,
        typeNames:names.join(' - '),
        orderDetailId:obj.orderDetailId,
        orderDetailInedx:obj.orderDetailInedx,
        detailIndex:obj.detailIndex
      })

      //从订单传来的售后类型
      if(obj.afterSalesType){
        let id = 'editInfo.afterSalesType';
        let name = 'editInfo.afterSalesTypeName';
        let str = '';
        if(obj.afterSalesType=='online'){
          str = '线上';
        }else if(obj.afterSalesType=='offline'){
          str = '线下';
        }
        this.setData({
          [id]: obj.afterSalesType,
          [name]: str
        })
      }

      // this.autoSelectRegion(obj.projectIdFid);
      // //查询项目fid
      // if(obj.projectId){
      //   this.getProjectFid(obj.projectId);
      // }
      //查询大区，查询项目的父级并且是大区的，如果没有就取父级
      this.getRegion(obj);

      //查询项目名称
			this.getProjectName(obj.projectId);
    }
  },

  getRegion(obj){
    let param ={}
    //判断rid不等于空并且不等于0
    if(obj.projectRid != null && obj.projectRid !="" && obj.projectRid != 0){
      param={
        isAuth:true,
        className:'depart',
        data:{
          nbl:Base64.encode(util.timeFormatDay(new Date())),
          searchAll:true,
          id:obj.projectRid,
          selectFields:["id","name"]
        }
      }
    }else{
      param={
        isAuth:true,
        className:'depart',
        data:{
          nbl:Base64.encode(util.timeFormatDay(new Date())),
          searchAll:true,
          id:obj.projectIdFid,
          selectFields:["id","name"]
        }
      }
    }
    CommonService.goFindList(param).then(res=>{
      let result=res.data.data.result[0];
      this.setData({
        regionId: result.id,
        regionName: result.name
      })
    }).catch((error) => {
    })
  },

  //获取设备信息#
  getEquipmentInfo(){
    let param={
      isAuth:false,
      className:'equipment',
      data:{
        id:this.data.equipmentId,
        selectFields:['id','imei','equipmentNo','businessType','equipmentBaseName','equipmentAlias','typeArr','categoryArr',
        'regionId','region','projectId','project','memberTypeName','memberTypeId','memberType','iconUrl','workAmount',
        'workUnit','chargingMode','memberId','member','factoryId','factory','equipmentBaseId',
        'equipmentBase','dealerId','dealer','cleaningSupplierId','cleaningSupplier','cleaningSupplierProjectId',
        'cleaningSupplierProject','ownerIds','editerIds','oldImei',"orderNo","orderDetailInedx","orderDetailId",
        "purchaseOrderId","isfactoryBindNew","detailIndex","centreId","centre","createDate","standardDuration",
          "renewalInfo","battery","waterTank", "batteryCapacity","bilgeTank","brand","afterSalesType","editImeiInfo"]
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result){
        let result=res.data.data.result[0];

        //处理业务类型显示名称
        if(result.businessType){
          let bList=this.data.businessTypeList;
          bList.forEach(item => {
            if (item.id==result.businessType){
              result.businessTypeName=item.text;
            }
          });
        }

        //处理售后类型
        if(result.afterSalesType){
          let str = '';
          if(result.afterSalesType=='online'){
            str = '线上';
          }else if(result.afterSalesType=='offline'){
            str = '线下';
          }
          result.afterSalesTypeName = str;
        }

        //处理项目的数据权限（用于加到设备中）
        if(result.project && result.project.length){
          let pObj = result.project[0];
          if(pObj.dataAuthority && pObj.dataAuthority.depart && pObj.dataAuthority.depart.length){
            result.projectDataAuthority = pObj.dataAuthority.depart;
          }
        }

        this.setData({
          editInfo: result
        })

        //编辑设备时获取各个字段的值
        this.getInputValue();
      }
    }).catch((error) => {
    })
  },

  //编辑设备时获取各个字段的值
  getInputValue(){
    let info=this.data.editInfo;

    console.log('修改设备信息回显');
    console.log(info);

    //客户设备型号
    let memberTypeStr='';
    //图片
    let headImg='';
    //清洁工作量（面积/里程）
    let workAmount=0;
    //l
    let standardDuration = 0

    let chargeId = 0
    let chargeName = ""

    //处理客户设备型号
    if(info.memberTypeName){
      memberTypeStr=info.memberTypeName;
    }else if(info.memberType.length && info.memberType[0].name){
      memberTypeStr=info.memberType[0].name;
    }else if(info.equipmentBase.length && info.equipmentBase[0].typeCode){
      memberTypeStr=info.equipmentBase[0].typeCode;
    }

    //回显充电方式
    if(info.chargingMode != null && info.chargingMode == 1){
      chargeId = 1
      chargeName = "蓄电池直充"
    } else if(info.chargingMode != null && info.chargingMode == 2){
      chargeId = 2
      chargeName = "设备外充"
    }

    //处理图片
    if(info.iconUrl){
      headImg=info.iconUrl
    }else if(info.memberType.length && info.memberType[0].iconUrl){
      headImg=info.memberType[0].iconUrl
    }

    //去掉图片url的乱码
    if(headImg && headImg.indexOf("?")!=-1){
      let index = headImg.indexOf("?");
      if (index != -1) {
        headImg = headImg.substring(0, index);
      }
    }

    //处理清洁工作量
    if(info.workAmount){
      workAmount=info.workAmount;
    }else if(info.cleanArea){
      workAmount=info.cleanArea;
    }else if(info.memberType.length && info.memberType[0].cleanArea){
      workAmount=info.memberType[0].cleanArea;
    }

    console.log("info.standardDuration");
    console.log(info.standardDuration);
    if (info.standardDuration != null){
      standardDuration = info.standardDuration
    }
    //处理设备类型名称
    let names=[];
    if(info.categoryArr && info.categoryArr.length){
      //按id排序
      info.categoryArr.sort(util.compareobjectArray('id',1));
      let typeNames=info.categoryArr;
      typeNames.forEach(item => {
        names.push(item.name);
      });
    }

    //处理所有权
    if(info.ownerIds && info.ownerIds.length){
      if(info.ownerIds[0]==info.memberId){
        this.setData({
          owner: '1'
        })
      }else{
        this.setData({
          owner: '2'
        })
      }
    }

    //处理修改权
    if(info.editerIds && info.editerIds.length){
      let editerArr=[];
      if(info.editerIds.indexOf(info.memberId)!=-1){
        editerArr.push('1');
      }
      if(info.editerIds.indexOf(info.cleaningSupplierId)!=-1){
        editerArr.push('2');
      }
      this.setData({
        editer: editerArr
      })
    }
    //如果是从订单绑定的设备需要修改的时候，equipmentBaseName用带过来的是值
    let equipmentBaseStr = "";
    if(info.businessType != null){
      equipmentBaseStr = info.equipmentBaseName;
    }else{
      equipmentBaseStr = info.equipmentBase.length?info.equipmentBase[0].typeCode:'';
    }

    this.setData({
      imei:info.imei,
			projectId:info.projectId ? info.projectId : '',
      projectName:info.project.length ? info.project[0].name : '',
      headImg:headImg ? headImg : '/images/nothing.jpg',
      memberTypeStr:memberTypeStr,
      memberTypeName:memberTypeStr,
      workAmount:workAmount,
      memberTypeId:info.memberTypeId ? info.memberTypeId : null,
      equipmentBaseId:info.equipmentBaseId ? info.equipmentBaseId : '',
      equipmentBaseName:equipmentBaseStr,
      memberId:info.memberId ? info.memberId : '',
      memberName:info.member.length ? info.member[0].name : '',
      dealerId:info.dealerId ? info.dealerId:'',
      dealerName:info.dealer.length ? info.dealer[0].name : '',
      workUnit:info.workUnit ? info.workUnit : '',
      workUnitStr:info.workUnit ? info.workUnit+'/小时' : '',
      typeIds:info.typeArr,
      typeNames:names.join(' - '),
      factoryId:info.factoryId,
      cleaningSupplierId:info.cleaningSupplierId ? info.cleaningSupplierId : null,
      cleaningSupplierName:info.cleaningSupplier.length ? info.cleaningSupplier[0].name : '',
      cleaningSupplierProjectId:info.cleaningSupplierProjectId ? info.cleaningSupplierProjectId : null,
      cleaningSupplierProjectName:info.cleaningSupplierProject.length ? info.cleaningSupplierProject[0].name : '',
      regionId:info.regionId ? info.regionId : null,
      regionName:info.region.length ? info.region[0].name : '',
      regionObj:info.region ? info.region : null,
      businessType:info.businessType ? info.businessType : null,
      orderNo:info.orderNo,
      orderDetailId:info.orderDetailId,
      orderDetailInedx : info.orderDetailInedx,
      purchaseOrderId : info.purchaseOrderId,
      isfactoryBindNew:info.isfactoryBindNew,
      detailIndex:info.detailIndex,
      brand:info.brand,
      chargeId:chargeId,
      chargeName:chargeName,
      standardDuration:standardDuration,
    })
  },

  //检测数组中是否含有某个值
  isAddDepart(arr,str){
    if(arr.length){
      return arr.every(item=>{
        return item!=str;
      });
    }else{
      return true;
    }
  },

  //表单点击确认添加设备##
  onConfirmAdd(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let td=this.data;
    let user=app.globalData.userInfo;
    let pro=e.detail.value;

    let showNo=td.showNo;

    let imei=pro.imei.trim();
    let equipmentAlias=pro.equipmentAlias.trim();

    let equipmentNo='';

    if(showNo){
      //如果允许输入equipmentNo
      equipmentNo=pro.equipmentNo.trim();
    }else{
      //之前的设备equipmentNo不变；新加的设备equipmentNo自动生成，时间戳+imei后六位
      if(td.isEdit){
        equipmentNo=td.editInfo.equipmentNo;
      }else{
        let dates=(util.timeFormatDay(new Date())).replaceAll('-','');
        let last6=imei.substring(imei.length-6);
        equipmentNo=dates + last6;
      }
    }

    //清洁面积/里程
    let workAmount=pro.workAmount.trim();

    //客户名称
    let memberName='';
    //合伙人名称
    let partnerName='';
    let searchKeyArr=td.searchKey;

    //采购订单传来的值
    let factoryBindObj = this.data.factoryBind;

    //非空验证
    if(!this.formNotEmpty(imei,'imeiMessage','请输入物联网编码')){
      return;
    }

    if(showNo){
      if(!this.formNotEmpty(equipmentNo,'equipmentNoMessage','请输入设备编码')){
        return;
      }
    }

    if(!this.formNotEmpty(workAmount,'workAmountMessage','请输入清洁面积/里程')){
      return;
    }
    if(!this.formNotEmpty(td.workUnitStr,'workUnitMessage','请选择单位')){
      return;
    }

    let waterTank = null;
    if(this.data.waterTankShow){
      waterTank = pro.waterTank.trim();
      if(!this.formNotEmpty(waterTank,'waterTankMessage','请输入清水箱')){
        return;
      }
    }else{
      waterTank = td.editInfo.waterTank;
    }

    let batteryCapacity = null;
    if(this.data.batteryCapacityShow){
      batteryCapacity = pro.batteryCapacity.trim()
      if(!this.formNotEmpty(batteryCapacity,'batteryCapacityMessage','请输入电池容量')){
        return;
      }
    }else{
      batteryCapacity = td.editInfo.batteryCapacity;
    }

    let bilgeTank = null;
    if(this.data.bilgeTankShow){
      bilgeTank = pro.bilgeTank.trim();
      if(!this.formNotEmpty(bilgeTank,'bilgeTankMessage','请输入污水箱')){
        return;
      }
    }else{
      bilgeTank = td.editInfo.bilgeTank;
    }

    if(this.data.brandShow){
      if(!this.formNotEmpty(pro.brand.trim(),'brandMessage','请输入品牌')){
        return;
      }
    }

    //电池类型和电压值必填
    if(!td.editInfo.battery || !td.editInfo.battery.batteryTypeId){
      Toast.fail('请选择电池类型');
      return;
    }
    if(!td.editInfo.battery || !td.editInfo.battery.volts){
      Toast.fail('请选择电压值');
      return;
    }

    //验证imei，equipmentNo，设备别名的重复性
    let editImei=td.imei;
    let editAlias=td.editInfo.equipmentAlias;
    let editNo=td.editInfo.equipmentNo;

    let flagImei=true;
    let flagAlias=true;
    let flagNo=true;

    let promiseArr=[];

    if(td.isEdit && (editImei==imei)){
    }else{
      flagImei=this.isExist(imei).then(value =>{
        if(value){
          this.setData({
            imeiMessage: '此编码已绑定设备',
            disabled:true
          })
        }
        return !value;
      });
    }

    if(td.isEdit && (editAlias==equipmentAlias)){
    }else{
      if(equipmentAlias){
        flagAlias=this.isExistAlias(equipmentAlias).then(value =>{
          if(value){
            this.setData({
              equipmentAliasMessage: '设备名称重复',
              disabled:true
            })
          }
          return !value;
        });
      }
    }

    if(showNo){
      if(td.isEdit && (editNo==equipmentNo)){
      }else{
        flagNo=this.isExistNo(equipmentNo).then(value =>{
          if(value){
            this.setData({
              equipmentNoMessage: '设备编码重复',
              disabled:true
            })
          }
          return !value;
        });
      }
      promiseArr.push(flagNo);
    }

    //业务类型必填
    let authority=this.data.authority;
    if(authority.iot.equipmentList.businessType && (td.myAppId==3 || td.myAppId==7)){
      if(!td.businessType){
        Toast.fail('请选择业务类型');
        return;
      }
    }

    promiseArr.push(flagImei,flagAlias);

    let memberId=null;
    let factoryId=null;
    let partnerId=null;
    let dealerId=null;

    //权限
    let authDepart=[];

    //如果是天骏小程序，任何人绑设备都加入天骏的权限
    if(app.globalData.myAppId==6){
      authDepart.push(1806);
    }

    //如果是安装人员
    if(user.isIotInstaller==true){
      let partnerFlag=true;

      if(td.memberId){
        memberId=td.memberId;
        authDepart.push(memberId);

        //如果客户本身还是经销商
        if(td.memberOfType==7){
          dealerId=td.memberId;
        }

        //查询客户的合伙人
        partnerFlag=this.findPartner(memberId).then(value => {
          if(value){
            partnerId=value;
            authDepart.push(partnerId);
          }
          return true;
        });
      }
      promiseArr.push(partnerFlag);

      if(td.factoryId){
        factoryId=td.factoryId;
        authDepart.push(factoryId);
      }

    }else{
      //如果是客户
      if(user.typeHandle==4 && user.isIotInstaller!=true){
        if(td.memberId){
          memberId=td.memberId;
        }else{
          memberId=user.departObj[0].companyId;
        }
        authDepart.push(memberId,user.depart);

        if(user.departObj[0].partnerId){
          partnerId=user.departObj[0].partnerId;
          authDepart.push(partnerId);
        }

        //如果客户本身还是经销商
        if(user.departObj[0].type==7){
          dealerId=memberId;
        }

        if(td.factoryId){
          factoryId=td.factoryId;
          authDepart.push(factoryId);
        }
      }

      //如果是厂家
      if(user.typeHandle==2 && user.isIotInstaller!=true){
        if(!td.equipmentBaseId){
          Toast.fail('请选择设备型号');
          this.setData({
            disabled:true
          })
          return;
        }

        let partnerFlag=true;

        factoryId=user.departObj[0].id;
        authDepart.push(factoryId);

        dealerId=td.dealerId;
        authDepart.push(dealerId);

        if(td.memberId){
          memberId=td.memberId;
          authDepart.push(memberId);

          //查询客户的合伙人
          partnerFlag=this.findPartner(memberId).then(value => {
            if(value){
              partnerId=value;
              authDepart.push(partnerId);
            }
            return true;
          });
        }
        promiseArr.push(partnerFlag);
      }

      //如果是经销商
      if(user.departObj[0].type==7 && user.isIotInstaller!=true){
        dealerId=user.departObj[0].id;
        if(dealerId){
          authDepart.push(dealerId);
        }

        partnerId=user.departObj[0].id;
        authDepart.push(partnerId);

        if(td.memberId){
          memberId=td.memberId;
          authDepart.push(memberId);
        }
        if(td.factoryId){
          factoryId=td.factoryId;
          authDepart.push(factoryId);
        }
      }
    }

    //项目id
    if(td.projectId){
      authDepart.push(td.projectId, td.editInfo.fid);     
      //项目的权限直接加进去
      authDepart = authDepart.concat(td.editInfo.projectDataAuthority);
    }

    //大区id
    if(td.regionId){
      authDepart.push(td.regionId);
    }

    //清洁面积为数字
    if(workAmount!='' && workAmount!=null){
      if(!(/^\d+(\.\d+)?$/.test(workAmount))){
        this.setData({
          workAmountMessage: '清洁面积为数字',
          disabled: true
        });
        return;
      }
    }

    //水箱
    if(this.data.waterTankShow && waterTank!='' && waterTank!=null){
      if(!(/^\d+(\.\d+)?$/.test(waterTank))){
        this.setData({
          waterTankMessage: '清水箱为整数',
          disabled: true
        });
        return;
      }
    }else{
      if(!waterTank){
        waterTank = 0;
      }
    }

    //电池容量
    if(this.data.batteryCapacityShow && batteryCapacity!='' && batteryCapacity!=null){
      if(!(/^\d+(\.\d+)?$/.test(batteryCapacity))){
        this.setData({
          batteryCapacityMessage: '电池容量为整数',
          disabled: true
        });
        return;
      }
    }else{
      if(!batteryCapacity){
        batteryCapacity = 0;
      }
    }

    //污水箱
    if(this.data.bilgeTankShow && bilgeTank!='' && bilgeTank!=null){
      if(!(/^\d+(\.\d+)?$/.test(bilgeTank))){
        this.setData({
          bilgeTankMessage: '污水箱为整数',
          disabled: true
        });
        return;
      }
    }else{
      if(!bilgeTank){
        bilgeTank = 0;
      }
    }

    if(user.typeHandle==4 && user.isIotInstaller!=true){
      memberName=user.departObj[0].name;
    }else{
      memberName=td.memberName;
    }

    //将保洁供应方放入权限数组
    let cleaningSupplierId=null;
    if(td.cleaningSupplierId){
      cleaningSupplierId=td.cleaningSupplierId;
      authDepart.push(cleaningSupplierId);
    }else{
      //如果是天骏小程序
      if(app.globalData.myAppId==6){
        cleaningSupplierId=1806;
        authDepart.push(1806);
      }
    }

    if(td.cleaningSupplierProjectId){
      authDepart.push(td.cleaningSupplierProjectId);
    }

    //处理所有权和修改权
    let ownerIds=[],editerIds=[];
    if(td.owner){
      let owner=td.owner;
      if(owner=='1'){
        ownerIds.push(td.memberId);
        authDepart.push(td.memberId);
      }else{
        ownerIds.push(td.cleaningSupplierId);
        authDepart.push(td.cleaningSupplierId);
      }
    }else{
      //如果是天骏小程序
      if(app.globalData.myAppId==6){
        ownerIds.push(1806);
      }
    }

    if(td.editer){
      let editer=td.editer;
      if(editer.indexOf('1')!=-1){
        editerIds.push(td.memberId);
        authDepart.push(td.memberId);
      }
      if(editer.indexOf('2')!=-1){
        editerIds.push(td.cleaningSupplierId);
        authDepart.push(td.cleaningSupplierId);
      }
    }else{
      //如果是天骏小程序
      if(app.globalData.myAppId==6){
        editerIds.push(1806);
      }
    }

    if(factoryBindObj){
      //处理所有权
      if(td.ownerIds && td.ownerIds.length){
        ownerIds = td.ownerIds
      }
      //处理修改权
      if(td.editerIds && td.editerIds.length){
        editerIds = td.editerIds
      }
    }

    //处理oldImei
    let oldImei=td.editInfo.oldImei;
    //是否把oldimei同步到es数据库
    let isSyncEsOld = false;

    if(td.isEdit && td.editInfo.imei!=imei){
      oldImei=td.editInfo.imei;
      isSyncEsOld = true;
    }

    //处理设备类型
    let typeArrs=[];
    if(td.typeIds.length){
      typeArrs=[1].concat(td.typeIds);
      let typeSet=new Set(typeArrs);
      typeArrs=Array.from(typeSet);
    }else{
      Toast.fail('请选择设备类型');
      return;
    }

    //平台人员绑设备、或修改了imei时，先检验模块是否在仓库中。不在的需要走pc端入库出库流程
    // if(user.departObj[0].type==1){
    //   if(!td.isEdit || td.isEdit && td.editInfo.imei!=imei){
    //     let flagWare=true;
    //     flagWare=this.isExistWare(imei).then(value =>{
    //       if(!value){
    //         Toast({
    //           type: 'fail',
    //           message: '模块不在仓库中，请到管理后台进行入库和领用操作',
    //           duration: 3000,
    //         });
    //         this.setData({
    //           disabled: true
    //         })
    //       }
    //       return value;
    //     });
    //     promiseArr.push(flagWare);
    //   }
    // }

    Promise.all(promiseArr).then(value => {
      //查询合伙人名称
      if(partnerId){
        let partnerNameFlag=this.getDepartName(partnerId).then(value => {
          partnerName=value;
          return true;
        });
        promiseArr.push(partnerNameFlag);
      }  

      //设备型号
      let memberTypeName=pro.memberTypeName.trim();
      if(user.typeHandle!=2){
        if(!memberTypeName){
          Toast.fail('请输入或选择设备型号');
          return;
        }
      }

      //添加客户设备型号  added  by 毕研帅   2022-05-06
      if(td.isfactoryBindNew){
        if(td.memberTypeName!=null){
          memberTypeName=td.memberTypeName.trim();
        }
      }

      //客户必填
      if(authority.iot.equipmentList.member){
        if(!memberId){
          Toast.fail('请选择所属甲方公司');
          return;
        }
      }

      //项目必填
      if(authority.iot.equipmentList.project){
        if(!td.projectId){
          Toast.fail('请选择所属项目');
          return;
        }
      }

      Promise.all(promiseArr).then(value => {
        let passed=value.every(val=>{
          return val;
        });

        if(passed){
          //处理搜索词
          searchKeyArr.push(imei,equipmentNo,equipmentAlias,memberTypeName,memberName,td.projectName,td.factoryName,partnerName,td.regionName);
          let arrSet2=new Set(searchKeyArr);
          searchKeyArr=Array.from(arrSet2);

          let searchKey=[];
          searchKeyArr.forEach(item=>{
            if(item){
              searchKey.push(item);
            }
          });

          //处理权限(去掉空值和重复)
          let dataAuthorityArrNew=[];         
          authDepart.forEach(item => {
            if(item){
              dataAuthorityArrNew.push(item);
            }
          });
          let dataAuthoritySet=new Set(dataAuthorityArrNew);
          dataAuthorityArrNew=Array.from(dataAuthoritySet);          

          let parameter={
            className:'equipment',
            data:{
              requestToken:this.data.code,
              id:td.equipmentId,
              //物联网IMEI
              imei:imei,
              //设备编号
              equipmentNo:equipmentNo,
              //客户id
              memberId:memberId,
              //客户设备型号ID
              memberTypeId:td.memberTypeId,
              //客户设备型号名称
              memberTypeName:memberTypeName,
              //项目
              projectId:td.projectId,
              //项目ID,仅龙湖使用
              proID:td.proID,
              //大区
              regionId: td.regionId ? td.regionId : memberId,
              //大区名字
              region: td.regionName ? td.regionName : td.memberName,
              //图片
              iconUrl:td.headImg,
              //清洁工作量
              workAmount:Number(workAmount),
              //水箱
              waterTank: parseInt(waterTank),
              //电池容量
              batteryCapacity: parseInt(batteryCapacity),
              //污水箱
              bilgeTank: parseInt(bilgeTank),
              //品牌
              brand:pro.brand,
              //清洁单位
              workUnit:td.workUnit,
              //厂家id
              factoryId:factoryId,
              //厂家型号
              equipmentBaseId:td.equipmentBaseId,
              //厂家型号名称
              equipmentBaseName:td.equipmentBaseName,
              //经销商ID
              dealerId:dealerId,
              //合伙人id
              partnerId:partnerId,
              //充电方式
              chargingMode:td.chargeId,
              //保洁供应方id
              cleaningSupplierId:cleaningSupplierId,
              //保洁供应方项目id
              cleaningSupplierProjectId:td.cleaningSupplierProjectId,
              //所有权
              ownerIds:ownerIds,
              //修改权
              editerIds:editerIds,
              //权限
              dataAuthority:{
                depart:dataAuthorityArrNew,
                role:['iot_admin','admin','data_admin']
              },
              isVectorMotor:td.editInfo.isVectorMotor,
              searchKey:searchKey,
              typeArr:typeArrs,
              //设备别名
              equipmentAlias:equipmentAlias,
              //修改前的imei
              oldImei:oldImei,
              //区分什么业务类型的设备1.销售生成采购订单，2.租赁生成采购订单-授信,3.租赁生成采购订单-非授信,4.试机订单生产采购订单
              businessType:td.businessType,
              appId: [app.globalData.myAppId],
              //电池类型和电压值
              battery:{
                batteryTypeId: td.editInfo.battery.batteryTypeId,
                batteryTypeName: td.editInfo.battery.batteryTypeName,
                volts: td.editInfo.battery.volts,
                voltsName: td.editInfo.battery.voltsName,
                voltsValue: td.editInfo.battery.voltsValue,
                minVol: td.editInfo.battery.minVol,
                floats: td.editInfo.battery.floats
              },
              //售后类型：线上/线下售后（销售的设备才有）
              afterSalesType: td.editInfo.afterSalesType
            }
          }

          if(!td.isEdit){
            //创建人
            parameter.data.createUser=user.id;
          }

          //中心
          if(td.editInfo.centreId){
            parameter.data.centreId=td.editInfo.centreId;
            parameter.data.centre=td.editInfo.centre;
          }

          //added  by 毕研帅  2022-04-19 18:04
          //系统下单把一下信息存入设备表，做修改用
          if(td.isfactoryBindNew != null && td.isfactoryBindNew && parameter.data.id == null){
            parameter.data.orderNo=td.orderNo;
            parameter.data.orderDetailId = td.orderDetailId;
            parameter.data.orderDetailInedx = td.orderDetailInedx;
            parameter.data.purchaseOrderId = factoryBindObj.orderId;
            parameter.data.isfactoryBindNew = td.isfactoryBindNew;
            parameter.data.detailIndex = td.detailIndex;
          }

          //秦海文2023年2月17日添加
          let oldImeiQ=parameter.data.oldImei;

          //添加的时候
          if(!td.isEdit){
            //2023-6-28之后新加的设备都有此字段
            parameter.data.landi=1;
            //最大工作速度
            parameter.data.workSpeed=0;
          }

          //2024-4-17加字段，从采购订单来的：
          //赠送耗材套数（租赁和销售设备都有）
          if(factoryBindObj && factoryBindObj.consumableGiftNumber){
            parameter.data.consumableGiftNumber = factoryBindObj.consumableGiftNumber;
          }

          //修改imei时保存修改记录，方便维护人员查询（登录人员、时间、编码、客户、项目）
					if (td.isEdit && td.editInfo.imei != imei) {
						let editImeiInfo = td.editInfo.editImeiInfo || [];
						editImeiInfo.push({
							editTime: util.timeFormat(new Date()),
							userId: user.id,
							userName: user.userName,
							imei: imei,
              oldImei: oldImei,
							member: td.memberName,
							memberId: td.memberId,
							project: td.projectName,
							projectId: td.projectId
            });
						parameter.data.editImeiInfo = editImeiInfo;
					}

          //  console.log('###添加设备表单提交###');
					//  console.log(parameter.data);
					//回调测试
					//this.updateOldImeiState('update',imei,oldImei,memberName+'+'+td.projectName);					

        
          //避免表单重复提交
          Toast.loading({
            duration: 0,
            forbidClick: true,
            message: '数据提交中...'
          });

          CommonService.goSave(parameter).then(res=>{
            Toast.clear();
            this.setData({
              disabled:false
            })

            if (res.statusCode == 200 && res.data.success == true){
              if(td.isEdit){
                //修改内容记入日志
                this.equipmentLog(parameter.data, td.editInfo, memberName, td.projectName);
              }

              if(td.isfactoryBind){
                //更新洁邦尼订单中的设备
                //this.updateOrder(imei, equipmentNo);
              }else{
                Toast.success('成功');
                if(td.isfactoryBindNew != null && td.isfactoryBindNew && parameter.data.id == null){
                  //获取列表页对象
                  let pages = getCurrentPages();
                  let prevPage = pages[pages.length - 3];
                  prevPage.refreshListAndPage();
                  wx.navigateBack();
                }else{
                    //获取列表页对象
                    let pages = getCurrentPages();
                    let prevPage = pages[pages.length - 2];

                    //更新查询设备范围，返回列表页并刷新数据
                    if(prevPage.data.idArr.length){
                      prevPage.setData({
                        idArr: prevPage.data.idArr.concat(res.data.data)
                      })
                    }
                    wx.navigateBack();
                    prevPage.refreshListAndPage();
                }
              }             
             //关联查询字段更新到设备表
             this.updateEquipment(res.data.data.id, isSyncEsOld, oldImei,parameter.data.projectId);           

              //如果是厂家从采购订单里面绑的物联网需要更新订单信息中物联网信息
              if(td.isfactoryBindNew){
                this.updateOrderIotInfo(e,parameter);
              }

              //更新物联网仓库的状态
             this.updateIotWarehouse(parameter.data.imei);
							
							//2024-9-6修改：更换下来的旧模块归属仓库问题，调用新的请求，原来是updateIotOldImeiQWarehouse这个方法
							if (td.isEdit) {
								if(td.editInfo.imei!=imei){
									this.updateOldImeiState('update', imei, oldImei, memberName+'+'+td.projectName);
								}
							}else{
								//添加时也调用
								this.updateOldImeiState('add', imei, null, memberName+'+'+td.projectName);
							}

            }else if(res.statusCode==202){
              Toast.fail('您操作太快了,请勿重复提交');
            }
          }).catch((error) => {
            Toast.clear();
            Toast.fail('请求数据资源服务错误');
          })

        }
      });
    });
  },

  //added by 毕研帅  2022-04-20 18:04
  //绑定完物联网后把物联网编码跟设备编码更新到订单里面，
  //这个方法只用到采购订单里面帮物联网
  updateOrderIotInfo(e,parameter){
    //绑定完设备更新采购订单里面的状态
    //先根据订单id把订单查出来
    let id = 0 ;
    let detailIndex = 0;
    if(parameter.data.id != null && parameter.data.id != ""){
        id = this.data.purchaseOrderId;
        detailIndex = this.data.detailIndex;
    }else{
        id = this.data.factoryBind.orderId;
        detailIndex = this.data.factoryBind.detailIndex;
    }

    let param={
      isAuth:false,
      className:'purchaseOrder',
      data:{
        selectFields:["id","orderNo","member","createTime","sellAmount","purchaseAmount","state","member","orderId","supplier",
        "address","businessType","orderNo","relationOrderNo","kind","salesman","detail","project","servicer","numbers"],
        id:id
      }
    }
    CommonService.goFindList(param).then(res=>{
      //1.修改此订单未绑定的未定设备数量，在保存采购订单的时候就把此订单下的设备数量做了统计numbers这个字段
      //2.设备绑定后更新numbers，numbers等于数据库的numbers这个字段减1
      //3.绑定设备的时候把这台设备的下标（detailIndex）传过来了,根据下标获取订单中detail的对应的对象，
      //4.获取detail对象后再更新绑定的物联网编号
      let arr = res.data.data.result[0].detail
      for(let i=0;i<arr.length;i++){
        if (detailIndex == arr[i].orderIndex){
          let detailObj = arr[i]
					detailObj.imei = e.detail.value.imei.trim();
					if(e.detail.value.equipmentNo){
						detailObj.equipmentNo = e.detail.value.equipmentNo.trim();
					}
          detailObj.dataAuthority = parameter.data.dataAuthority
        }
      }
      let param = {}

      if(parameter.data.id != null && parameter.data.id != ""){
        param = {
          className:'purchaseOrder',
          data:{
            id:id,
            detail:res.data.data.result[0].detail
          }
        }
      }else{
         param = {
          className:'purchaseOrder',
          data:{
            id:id,
            numbers:res.data.data.result[0].numbers-1,
            detail:res.data.data.result[0].detail
          }
        }
      }
      CommonService.goSave(param).then(item=>{
      if (item.statusCode == 200 && item.data.success == true){

        //根据采购订单relationOrderNo查询租赁/销售/试机订单
        let tableName = "";
        if(this.data.businessType == 1 || this.data.businessType == 2 || this.data.businessType == 3){
          tableName="order";
        }else if(this.data.businessType == 4){
          tableName="tryOrder";
        }
        let param1={
          isAuth:false,
          className:tableName,
          data:{
            selectFields:["id","orderNo","splitDetail","type"],
            orderNo:this.data.orderNo
          }
        }

          CommonService.goFindList(param1).then(res1=>{
              for(let i=0;i<res1.data.data.result[0].splitDetail.length;i++){
                let orderDetail = res1.data.data.result[0].splitDetail[i];
                if(this.data.orderDetailId == orderDetail.id && this.data.orderDetailInedx == orderDetail.index){
                  orderDetail.imei = e.detail.value.imei.trim();
                  orderDetail.equipmentNo = e.detail.value.equipmentNo.trim();
                  orderDetail.dataAuthority = parameter.data.dataAuthority
                }
              }

              let orderParam = {
                className:tableName,
                data:{
                  id:res1.data.data.result[0].id,
                  splitDetail:res1.data.data.result[0].splitDetail
                }
              }
         
              CommonService.goSave(orderParam).then(res=>{

              })
       
              //更新t_purchase_equipment表
              this.updatePurchaseEquipment(res1,res);
             
              if(parameter.data.id == null){            
                    //获取列表页对象
                    let pages = getCurrentPages();
                    let prevPage = pages[pages.length - 2];
                    prevPage.refreshListAndPage();
                    wx.navigateBack();
              }
          })
      }

      })

    })
 },

    updatePurchaseEquipment(res1,res){
      let orderParam = {
        data:{
          orderNo:res.data.data.result[0].orderNo,
          splitDetail:res1.data.data.result[0].splitDetail
        }
      }
      CommonService.updatePurchaseEquipment(orderParam).then(res=>{

      })
    },


  //判断表单非空（涉及到数据提交，field可以在调用前去空格）
  formNotEmpty(field,messageField,messageCon){
    //field=field.trim();
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //验证imei重复
  isExist(imei){
    let param = {
      isAuth: false,
      className: 'equipment',
      data: {
        searchAll: true,
        imei:imei,
        selectFields: ['id'],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param,false).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.count) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //验证设备编码重复
  isExistNo(equipmentNo){
    let param = {
      isAuth: false,
      className: 'equipment',
      data: {
        searchAll: true,
        equipmentNo:equipmentNo,
        selectFields: ['id'],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param,false).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.count) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //验证设备别名重复
  isExistAlias(alias){
    let param = {
      isAuth: false,
      className: 'equipment',
      data: {
        searchAll: true,
        equipmentAlias:alias,
        selectFields: ['id']
      }
    }
    if(this.data.memberId){
      param.data.memberId=this.data.memberId;
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param,false).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.count) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //扫码-imei
  scanCode(e) {
    var that = this;
    wx.scanCode({
      success: (res) => {
        that.setData({
          imei: res.result
        })
      }
    })
  },

  //扫码-equipmentNo
  scanEquipmentNo(e) {
    var that = this;
    wx.scanCode({
      success: (res) => {
        let equipmentNo='editInfo.equipmentNo';
        that.setData({
          [equipmentNo]:res.result
        })
      }
    })
  },

  //显示厂家选择框
  onShowFactory(){
    this.setData({
			showFactory: true
    })

    let param={
      isAuth:true,
      className:'depart',
      data:{
        searchAll:true,
        type:2,
        selectFields:["id","name"]
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id
          }
          arr.push(obj);
        }
        this.setData({
          factoryList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏厂家选择框
  onCloseFactory(){
    this.setData({
			showFactory: false
    })
  },

  //确认厂家
  onConfirmFactory(e){
    this.setData({
      factoryId: e.detail.value.id,
      factoryName: e.detail.value.text
    })
    this.onCloseFactory();
  },

  //选择设备型号，现在新订单的厂家设备型号在factory_equipment_type表里
  //判断isfactoryBindNew（新订单进入绑设备）是否为true,如果是true，设备想好从factory_equipment_type里查，为false跟之前一样
  changeFactoryType(){
      if(this.data.isfactoryBindNew || this.data.businessType != null){
        this.onShowFactoryTypeNew();
      }else{
        this.onShowFactoryType();
      }
  },

  //显示厂家设备型号选择框
  onShowFactoryType(){
    this.setData({
      showFactoryType: true
    })

    this.getFactoryType();
  },

  //获取厂家设备型号
  getFactoryType(){
    let user=app.globalData.userInfo;

    let param = {
        isAuth: false,
        className: 'equipmentBase',
        data: {
          searchAll: true,
          factoryId: user.departObj[0].id,
          selectFields: ['id','typeCode','iconUrl','cleanArea']
        }
      }

      CommonService.goFindList(param).then(res=>{
        if(res.data.data && res.data.data.result && res.data.data.result.length){
          let result=res.data.data.result;
          let arr=[];
          result.forEach(item => {
            arr.push({
              text:item.typeCode,
              id:item.id,
              obj:item
            });
          });
          this.setData({
            factoryTypeList: arr
          })
        }
      }).catch((error) => {
      })
  },

  onShowFactoryTypeNew(){
    let user=app.globalData.userInfo;

    this.setData({
      showFactoryType: true
    })

    //获取厂家设备型号数据
    let parameter = {
      className: 'factoryEquipmentType',
      data: {
        isAuth:false,
        searchAll: true,
        factoryId:user.departObj[0].id,
        selectFields: ['id', 'brandId','factoryId','name',"productName"]
      }
    }
    CommonService.goFindList(parameter).then(res=>{
      if(res.data.data.result){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id,
            obj:list[i]
          }
          arr.push(obj);
        }
        this.setData({
          factoryTypeList: arr
        })
      }
    }).catch((error) => {

    })
  },

  //隐藏厂家设备型号选择框
  onCloseFactoryType(){
    this.setData({
			showFactoryType: false
		})
  },

  //确认选择厂家设备型号
  onConfirmFactoryType(e){
    let obj= e.detail.value.obj;
    let memberTypeNameStr = e.detail.value.text;
    //如果是通过订单绑的设备，memberTypeName还是用带过来的值，这里选择厂家型号不受影响
    if(this.data.businessType != null){
      memberTypeNameStr = this.data.memberTypeName;
    }
    this.setData({
      equipmentBaseId: e.detail.value.id,
      equipmentBaseName: e.detail.value.text,
      memberTypeName:memberTypeNameStr,
      showFactoryType: false,
      disabled:false
    })

    if(obj.iconUrl){
      this.setData({
        headImg: obj.iconUrl,
        showUpload:false
      })
    }

    if(obj.cleanArea){
      this.setData({
        workAmount:obj.cleanArea
      })
    }
  },

  //显示选择经销商
  onShowDealer(){
    this.setData({
			showDealer: true
    })

    let param={
      isAuth:true,
      className:'depart',
      data:{
        searchAll:true,
        type:7,
        selectFields:["id","name"]
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id
          }
          arr.push(obj);
        }
        this.setData({
          dealerList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏选择经销商
  onCloseDealer(){
    this.setData({
			showDealer: false
		})
  },

  //确认选择经销商
  onConfirmDealer(e){
    this.setData({
      dealerId: e.detail.value.id,
      dealerName: e.detail.value.text
    })
    this.onCloseDealer();
  },

  //显示选择客户
  onShowMember(){
    this.setData({
			showMember: true
    })

    //查询客户
    this.findMember();
  },

  //查询客户
  findMember(){
    let param={
      isAuth:true,
      className:'depart',
      data:{
        isProject: false,
        isRegion: false,
        searchAll:true,
        selectFields:['id','name'],
        complex:[{
          "or": {
            type:4,
            multiType:4
          }
        }]
      }
    }

    //客户名称模糊查询
    if(this.data.valueSearchMember){
      param.data.name='%'+this.data.valueSearchMember+'%'
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id,
            type:list[i].type
          }
          arr.push(obj);
        }
        this.setData({
          memberList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏选择客户
  onCloseMember(){
    this.setData({
			showMember: false
		})
  },

  //确认选择客户
  onConfirmMember(e){
    this.setData({
      memberId: e.detail.value.id,
      memberName: e.detail.value.text,
      memberOfType: e.detail.value.type,
      disabled: false
    })
    this.onCloseMember();
  },

  //改变客户-重置客户型号和项目和大区
  onChangeMember(){
    this.setData({
      memberTypeId: null,
      memberTypeStr: '',
      projectId: null,
      projectName: '',
      regionId: null,
      regionName: '',
      regionList:[]
    })
  },

  //显示客户设备型号选择框
  onShowUserType(){
    let user=app.globalData.userInfo;
    let memberId=null;

    if(user.isIotInstaller==true){
      memberId=this.data.memberId;
      if(!memberId){
        Toast.fail('请先选择甲方公司');
        return;
      }
    }else{
      memberId=user.departObj[0].companyId
    }

    this.setData({
			showUserType: true
    })

    let param = {
      isAuth: false,
      className: 'equipmentMemberType',
      data: {
        searchAll: true,
        memberId: memberId,
        selectFields: ['id','name','iconUrl','cleanArea'],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          userTypeList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏客户设备型号选择框
  onCloseUserType(){
    this.setData({
			showUserType: false
		})
  },

  //确认选择客户设备型号
  onConfirmUserType(e){
    let obj=e.detail.value.obj;

    this.setData({
      memberTypeId: e.detail.value.id,
      memberTypeStr: e.detail.value.text,
      showUserType: false
    });

    if(obj.iconUrl){
      this.setData({
        headImg: obj.iconUrl,
        showUpload:false
      })
    }

    if(obj.cleanArea){
      this.setData({
        workAmount:obj.cleanArea
      })
    }
  },

  //显示项目选择框
  onShowProject(){
    let user=app.globalData.userInfo;
    if(user.isIotInstaller==true || user.departObj[0].type==7 || user.departObj[0].type==1){
      if(this.data.memberId){
        this.setData({
          showProject: true
        })
        //获取项目数据
        this.getProjectData();
      }else{
        Toast.fail('请先选择甲方公司');
      }
    }else{
      this.setData({
        showProject: true
      })
      //获取项目数据
      this.getProjectData();
    }
  },

  //获取项目数据
  getProjectData(){
    let param={
      isAuth:true,
      className:'depart',
      data:{
        searchAll: true,
        isProject: true,
        selectFields:["id","name","fid","rid","proID","dataAuthority",'cleaningSupplierObj'],
        complex:[{
          "or": {
            type:4,
            multiType:4
          }
        }],
        sort:{
          createDate:-1
        },
      }
    }

    //项目名称模糊查询
    if(this.data.valueSearchProject){
      param.data.name='%'+this.data.valueSearchProject+'%'
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data){
        let list=res.data.data.result;    

        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text: list[i].name,
            id: list[i].id,
            fid: list[i].fid,
            rid: list[i].rid,
            proID:list[i].proID,
            dataAuthority: list[i].dataAuthority.depart,
            cleaningSupplierObj: list[i].cleaningSupplierObj
          }
          arr.push(obj);
        }
        this.setData({
          projectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏项目选择框
  onCloseProject(){
    this.setData({
			showProject: false
		})
  },

  //确认项目
  onConfirmProject(e){
    let fid = 'editInfo.fid';
    let projectDataAuthority = 'editInfo.projectDataAuthority';
    let val = e.detail.value; 

    this.setData({
      projectId: val.id,
      projectName: val.text,
      //项目的父级
      [fid]: val.fid,
      disabled: false,
      proID: val.proID,
      //项目的数据权限
      [projectDataAuthority]: val.dataAuthority
    })

    //自动选择大区
    if(!this.data.regionId){
      this.autoSelectRegion(val.rid);
    }

    //项目的保洁供应方保存到设备中
    if(val.cleaningSupplierObj && val.cleaningSupplierObj.length){
      this.setData({
        cleaningSupplierId: val.cleaningSupplierObj[0].id,
        cleaningSupplierName: val.cleaningSupplierObj[0].name
      })
    }else{
      this.setData({
        cleaningSupplierId: null,
        cleaningSupplierName: ''
      })
    }

    this.onCloseProject();
  },

  //自动选择大区
  autoSelectRegion(id){
    let param={
      isAuth:true,
      className:'depart',
      data:{
        nbl:Base64.encode(util.timeFormatDay(new Date())),
        searchAll:true,
        id:id,
        selectFields:["id","name"]
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];
        this.setData({
          regionId: result.id,
          regionName: result.name
        })
      }
    }).catch((error) => {
    })
  },

  //显示上传图片组件
  onShowUpload(){
    this.setData({
			showUpload: true
		})
  },

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgArr=data.detail;
    if(imgArr.length){
      this.setData({
        headImg: imgArr[0]
      })
    }
  },

  //跳转添加项目
  goToAddDepart(){
    let user=app.globalData.userInfo;
    let companyId=null,
        companyName='';

    if(user.departObj[0].type==4){
      companyId=user.depart;
      companyName=user.departObj[0].name;
    }else{
      if(this.data.memberId){
        companyId=this.data.memberId;
        companyName=this.data.memberName;
      }else{
        Toast.fail('请先选择甲方公司');
        return;
      }
    }

    let obj={
      companyId: companyId,
      companyName: companyName,
      regionId: this.data.regionId,
      rid: this.data.regionId,
      regionName: this.data.regionName
    }

    wx.navigateTo({
      url: "/pages/departAdd/departAdd?paramObj="+JSON.stringify(obj)
    })
  },

  //显示选择清洁单位
  onShowWorkUnit(){
    this.setData({
      showWorkUnit: true,
      workUnitMessage:'',
      disabled:true
    })
  },

  //隐藏选择清洁单位
  onCloseWorkUnit(){
    this.setData({
			showWorkUnit: false
    })
  },

  //确认选择清洁单位
  onConfirmWorkUnit(e){
    this.setData({
      workUnit: e.detail.value.workUnit,
      workUnitStr: e.detail.value.text,
      disabled:false
    })
    this.onCloseWorkUnit();
  },

  //显示选择充电方式
  onShowCharge(){
    this.setData({
			showCharge: true
    })
  },

  //隐藏选择充电方式
  onCloseCharge(){
    this.setData({
			showCharge: false
    })
  },

  //确认选择充电方式
  onConfirmCharge(e){
    console.log(e);
    this.setData({
      chargeId: e.detail.value.id,
      chargeName: e.detail.value.text
    })
    this.onCloseCharge();
  },

  //更新洁邦尼订单中的设备
  updateOrder(imei,equipmentNo){
    let param={
      className:'deliverGoodsItems',
      data:{
        id: this.data.factoryBind.id,
        imei: imei,
        equipmentNo: equipmentNo
      }
    }

    CommonService.goSave(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        if(this.data.isEdit){
          Toast.success('成功');
          //返回
          this.backAndRefresh();
        }else{
          //更新洁邦尼订单的状态
          this.updateOrderState();
        }
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //更新洁邦尼订单的状态
  updateOrderState(){
    let param={
      className:'deliverGoods',
      data:{
        filter: {
          id:this.data.factoryBind.orderId
        },
        update: {
          set: {
            numbers:this.data.factoryBind.numbers-1
          }
        }
      }
    }

    CommonService.goUpdate(param).then(res=>{
      if (res.statusCode == 200 && res.data.code == 200){
        Toast.success('成功');
        //返回
        this.backAndRefresh();
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 3];
    prevPage.refreshListAndPage();
    wx.navigateBack({
      delta: 2
    })
  },

  //查询合伙人
  findPartner(depart){
    let param={
      isAuth:false,
      className:'depart',
      data:{
        id:depart,
        selectFields:["id","partnerId"]
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data) {
          let result=res.data.data.result[0];
          if(result.partnerId){
            resolve(result.partnerId);
          }else{
            resolve(null);
          }
        } else {
          resolve(null);
        }
      }).catch((error) => {
        resolve(null);
      })
    });
  },

  //绑定kafka分区
  bindKafka(imei){

    let param={
      imei:imei
    }
    CommonService.bindPartition(param).then(res=>{
    }).catch((error) => {
    })
  },

  //根据id查询depart名称
  getDepartName(id){
    let param={
      isAuth:false,
      className:'depart',
      data:{
        id:id,
        selectFields:["id","name"]
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.result.length) {
          let result=res.data.data.result[0];
            resolve(result.name);
        } else {
          resolve(null);
        }
      }).catch((error) => {
        resolve(null);
      })
    });
  },

  //查询设备一级分类
  findEquipmentCategory(){
    let param = {
      isAuth: false,
      className: 'equipmentCategory',
      data: {
        searchAll: true,
        fid: 1,
        selectFields: ["id", "fid", "name","sorts"],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
        sort:{
          sorts: 1
        }
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let cateArr=[];
        result.forEach(item => {
          cateArr.push({
            id:item.id,
            text:item.name,
          });
        });
        this.setData({
          typeOne: cateArr
        })
        //查询子分类
        this.findChildren(result[0].id);
      }
    }).catch((error) => {
    })
  },

  //查询子分类
  findChildren(fid){
    let param = {
      isAuth: false,
      className: 'equipmentCategory',
      data: {
        searchAll: true,
        fid: fid,
        selectFields: ["id", "fid", "name"],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    CommonService.goFindList(param).then(res=>{
      let typeOne=this.data.typeOne;
      //处理分类数据格式
      let typeList=[{
        values: typeOne,
        className: 'column1'
      }]

      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let cateArr=[];
        result.forEach(item => {
          cateArr.push({
            id:item.id,
            text:item.name,
          });
        });
        typeList.push({
          values: cateArr,
          className: 'column2'
        });
      }else{
        typeList.push({
          values: [],
          className: 'column2'
        });
      }

      this.setData({
        typeList: typeList
      })
    }).catch((error) => {
    })
  },

  //显示设备类型选择框
  onShowType(){
    this.setData({
			showType: true
    })
    //查询一级
    this.findEquipmentCategory();
  },

  //隐藏设备类型选择框
  onCloseType(){
    this.setData({
			showType: false
    })
  },

  //选择设备类型
  onChangeType(event) {
    const { picker, value, index } = event.detail;
    let arr=picker.getValues();
    this.findChildren(arr[0].id);
  },

  //确认设备类型
  onConfirmType(e){
    let arr=e.detail.value;
    let idArr=[],nameArr=[];

    arr.forEach(item => {
      if(item){
        idArr.push(item.id);
        nameArr.push(item.text);
      }
		});

    this.setData({
      typeIds: idArr,
      typeNames: nameArr.join(' - '),
      disabled:false
    })
    this.onCloseType();
  },

  //显示保洁供应方
  onShowCleaningSupplier() {
    this.setData({
      showCleaningSupplier: true
    })
    //查询保洁供应方
    this.getCleaningSupplier();
  },

  //查询保洁供应方
  getCleaningSupplier() {
    let param={
      className:'depart',
      data:{
        searchAll:true,
        type:4,
        selectFields:["id","name"],
        isCleaningSupplier:true
      }
    }

    //如果是非平台登录的，不按数据权限查，并加一个共有客户的条件
    let user = this.data.userInfo;
    if(user.type!=1){
      param.data.nbl = Base64.encode(util.timeFormatDay(new Date()));
      param.data.associationMember = [user.depart];
    }

    //名称模糊查询
    if(this.data.valueSearchCleaning){
      param.data.name='%'+this.data.valueSearchCleaning+'%'
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id
          }
          arr.push(obj);
        }
        this.setData({
          cleaningSupplierList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏保洁供应方
  onCloseCleaningSupplier() {
    this.setData({
      showCleaningSupplier: false
    })
  },

  //确认保洁供应方
  onConfirmCleaningSupplier(e){
    this.setData({
      cleaningSupplierId: e.detail.value.id,
      cleaningSupplierName: e.detail.value.text
    })
    this.onCloseCleaningSupplier();
  },

  //选择保洁供应方-搜索
  onChangeCleaning(e){
    this.setData({
      valueSearchCleaning: e.detail
    })

    //获取保洁供应方数据
    this.getCleaningSupplier();
  },

  //显示保洁供应方项目
  onShowCleaningSupplierProject() {
    if(this.data.cleaningSupplierId){
      this.setData({
        showCleaningSupplierProject: true
      })
      //查询保洁供应方项目
      this.getCleaningSupplierProject();
    }else{
      Toast.fail('请先选择保洁供应方');
    }
  },

  //查询保洁供应方项目
  getCleaningSupplierProject() {
    let param={
      isAuth:false,
      className:'depart',
      data:{
        searchAll:true,
        companyId:this.data.cleaningSupplierId,
        level:{"!=":1},
        selectFields:["id","name"]
      }
    }

    //名称模糊查询
    if(this.data.valueSearchCleaningProject){
      param.data.name='%'+this.data.valueSearchCleaningProject+'%'
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id
          }
          arr.push(obj);
        }
        this.setData({
          cleaningSupplierProjectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏保洁供应方项目
  onCloseCleaningSupplierProject() {
    this.setData({
      showCleaningSupplierProject: false
    })
  },

  //确认保洁供应方项目
  onConfirmCleaningSupplierProject(e){
    this.setData({
      cleaningSupplierProjectId: e.detail.value.id,
      cleaningSupplierProjectName: e.detail.value.text
    })
    this.onCloseCleaningSupplierProject();
  },

  //选择保洁供应方项目-搜索
  onChangeCleaningProject(e){
    this.setData({
      valueSearchCleaningProject: e.detail
    })

    //获取保洁供应方项目数据
    this.getCleaningSupplierProject();
  },

  //选择客户-搜索
  onChangeMemberName(e){
    this.setData({
      valueSearchMember: e.detail
    })

    //查询客户
    this.findMember();
  },

  //选择项目-搜索
  onChangeProjectName(e){
    this.setData({
      valueSearchProject: e.detail
    })

    //获取项目数据
    this.getProjectData();
  },

  //所有权
  onChangeOwner(event) {
    this.setData({
      owner: event.detail,
    })
  },

  //修改权
  onChangeEditer(event) {
    this.setData({
      editer: event.detail,
    })
  },

  //改变保洁供应方-重置供方项目
  onChangeCleaningSupplier(){
    this.setData({
      cleaningSupplierProjectId: null,
      cleaningSupplierProjectName: ''
    })
  },

  //显示大区选择框
  onShowRegion(){
    let user=app.globalData.userInfo;
    if(user.isIotInstaller==true || user.departObj[0].type==7 || user.departObj[0].type==1){
      if(this.data.memberId){
        this.setData({
          showRegion: true
        })
        //获取大区数据
        this.getRegionData();
      }else{
        Toast.fail('请先选择甲方公司');
      }
    }else{
      this.setData({
        showRegion: true
      })
      //获取大区数据
      this.getRegionData();
    }
  },

  //获取大区数据
  getRegionData(){
    let param={
      isAuth:true,
      className:'depart',
      data:{
        searchAll:true,
        isRegion:true,
        selectFields:["id","name","level"]
      }
    }

    //大区名称模糊查询
    if(this.data.valueSearchRegion){
      param.data.name='%'+this.data.valueSearchRegion+'%'
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id,
            obj:list[i]
          }
          arr.push(obj);
        }
        this.setData({
          regionList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏大区选择框
  onCloseRegion(){
    this.setData({
      showRegion: false
		})
  },

  //确认大区
  onConfirmRegion(e){
    this.setData({
      regionId: e.detail.value.id,
      regionName: e.detail.value.text,
      regionObj:e.detail.value.obj
    })
    this.onCloseRegion();
  },

  //清除大区选择
  onCancelRegion(){
    this.setData({
      regionId: null,
      regionName: ''
    })
    this.onCloseRegion();
  },

  //改变大区-重置项目
  onChangeRegion(){
    this.setData({
      projectId: null,
      projectName: ''
    })
  },

  //关联查询字段更新到设备表
  updateEquipment(id, isSyncEsOld, oldImei,projectId){
    let param={
      equipmentId:id
    }

    CommonService.updateEquipmentAll(param).then(res=>{
      //同步到es
      this.mongoToElastic(id, isSyncEsOld, oldImei,projectId);
    }).catch((error) => {
    })
  },

  //查询项目fid（从订单来的，需要根据项目查询大区）
  getProjectFid(projectId){
    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        nbl:Base64.encode(util.timeFormatDay(new Date())),
        id: projectId,
        selectFields: ['id','name','fid']
      }
    }
    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];
        this.autoSelectRegion(result.fid);
      }
    }).catch((error) => {
    })
  },

  //根据设备型号查询相关信息
  findFactoryType(){
    let user=app.globalData.userInfo;
    let memberTypeName=this.data.memberTypeName;
    let factoryId=user.departObj[0].id;

    let param = {
      isAuth: false,
      className: 'equipmentBase',
      data: {
        searchAll: true,
        factoryId: factoryId,
        typeCode: memberTypeName,
        selectFields: ["id","typeCode", "iconUrl","cleanArea"],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];
        this.setData({
          equipmentBaseId: result.id,
          equipmentBaseName: result.typeCode,
          headImg: result.iconUrl,
          showUpload:false,
          workAmount:result.cleanArea
        })
      }
    }).catch((error) => {
    })
  },

  //切换显示equipmentNo输入框
  onChangeNo({detail}) {
    this.setData({
      showNo: detail
    })
  },

  //显示业务类型选择框
  onShowBusinessType(){
    this.setData({
		showBusinessType: true
    })
  },

  //隐藏业务类型选择框
  onCloseBusinessType(){
    this.setData({
      showBusinessType: false
    })
  },

  //确认业务类型
  onConfirmBusinessType(e){
    let businessTypeName='editInfo.businessTypeName';
    this.setData({
      businessType: e.detail.value.id,
      [businessTypeName]: e.detail.value.text,
      disabled: false
    })
    this.onCloseBusinessType();
  },

  //跳转添加厂家型号
  goToAddFactoryType(){
    wx.navigateTo({
        url: "/packageA/pages/factoryTypeAdd/factoryTypeAdd"
    })
  },

  //显示选择框
  onShowSelect(e){
    let dataset=e.target.dataset;
    let field=dataset.field;

    this.setData({
      selectList: [],
      showSelect: true,
      selectField: field
    })

    //中心
    if(field=='centre'){
      let user=app.globalData.userInfo;
      if(user.isIotInstaller==true || user.departObj[0].type==7 || user.departObj[0].type==1){
        if(!this.data.memberId){
          Toast.fail('请先选择甲方公司');
          return;
        }
      }

      this.setData({
        selectTitle: '中心',
        showSelectSearch:true
      })
      this.getCentreList();
    }

    //电池类型
    if(field=='batteryType'){
      this.setData({
        selectTitle: '电池类型',
        showSelectSearch: false
      })
      this.getBatteryType();
    }

    //电压值
    if(field=='voltage'){
      if(this.data.editInfo.battery.batteryTypeId){
        this.setData({
          selectTitle: '电压值',
          showSelectSearch: false
        })
        this.getVoltageList();
      }else{
        Toast.fail('请先选择电池类型');
        return;
      }
    }

    //售后类型
    if(field=='afterSalesType'){
      this.setData({
        selectTitle: '售后类型',
        showSelectSearch: false
      })
      this.setData({
        selectList: [{
          id: 'online',
          text: '线上'
        },{
          id: 'offline',
          text: '线下'
        }]
      })
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //中心
    if(selectField=='centre'){
      id='editInfo.centreId';
      name='editInfo.centre';
    }

    //电池类型
    if(selectField=='batteryType'){
      id='editInfo.battery.batteryTypeId';
      name='editInfo.battery.batteryTypeName';
    }

    //电压值
    if(selectField=='voltage'){
      id='editInfo.battery.volts';
      name='editInfo.battery.voltsName';

      let obj = e.detail.value.obj;
      let volts = 'editInfo.battery.voltsValue';
      let minVol = 'editInfo.battery.minVol';
      let floats = 'editInfo.battery.floats';

      this.setData({
        [volts]: obj.volts,
        [minVol]: obj.minVol,
        [floats]: obj.floats
      })
    }

    //售后类型
    if(selectField=='afterSalesType'){
      id='editInfo.afterSalesType';
      name='editInfo.afterSalesTypeName'; 
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]: e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //中心
    if(selectField=='centre'){
      id='editInfo.centreId';
      name='editInfo.centre';
    }

    //电池类型
    if(selectField=='batteryType'){
      id='editInfo.battery.batteryTypeId';
      name='editInfo.battery.batteryTypeName';
    }

    //电压值
    if(selectField=='voltage'){
      id='editInfo.battery.volts';
      name='editInfo.battery.voltsName';
    }

    //售后类型
    if(selectField=='afterSalesType'){
      id='editInfo.afterSalesType';
      name='editInfo.afterSalesTypeName';
    }

    if(id && name){
      this.setData({
        [id]:null,
        [name]:''
      })
    }

    if(obj){
      this.setData({
        [obj]:null
      })
    }

    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //中心
    if(selectField=='centre'){
      this.getCentreList();
    }
  },

  //选择框改变
  onChangeSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null;

    //电池类型
    if(selectField=='batteryType'){
      id='editInfo.battery.volts';
      name='editInfo.battery.voltsName';
    }

    if(id && name){
      this.setData({
        [id]:null,
        [name]:''
      })
    }
  },

  //查询中心
  getCentreList(){
    let param = {
      isAuth:true,
      className:'depart',
      data:{
        searchAll:true,
        selectFields:["id","name"],
        companyId:this.data.memberId,
        id:{
          '!=':this.data.memberId
        }
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //修改内容记入日志
  equipmentLog(obj, info, memberName, projectName){
    let user=this.data.userInfo;
    let arr=[];

    //imei
    if(obj.imei!=info.imei){
      arr.push(info.imei +'->'+ obj.imei);
    }

    //equipmentNo
    if(obj.equipmentNo!=info.equipmentNo){
      arr.push(info.equipmentNo +'->'+ obj.equipmentNo);
    }

    //客户
    if(memberName){
      if(info.member && info.member.length && info.member[0].name){
        if(memberName!=info.member[0].name){
          arr.push(info.member[0].name +'->'+ memberName);
        }
      }else{
        arr.push('无客户' +'->'+ memberName);
      }
    }

    //项目
    if(projectName){
      if(info.project && info.project.length && info.project[0].name){
        if(projectName!=info.project[0].name){
          arr.push(info.project[0].name +'->'+ projectName);
        }
      }else{
        arr.push('无项目' +'->'+ projectName);
      }
    }

    if(arr.length){
      let param={
        className:'equipmentLog',
        data:{
          id: null,
          //操作人
          operator:{
            id: user.id,
            name: user.userName
          },
          //时间
          createTime: util.timeFormat(new Date()),
          //入口
          entrance: "小程序",
          //修改内容
          content: arr.toString(),
          //设备表id
          equipmentId: info.id,
          //当前设备编码
          equipmentNo:  obj.equipmentNo
        }
      }

      CommonService.goSave(param).then(res=>{
      });
    }
	},
	
  //秦海文2023年2月17日添加/////////////////////////////////////////////////////////////////////////////////////////////////////////
  //更换下来的旧模块归属仓库问题
  updateIotOldImeiQWarehouse(imei){
      let oldParam = {
        isAuth: false,
        className: 'imeiWarehouseInFactoryS',
        data: {
          imei: imei,
          state:1,////秦海文修改，不管仓库功能怎么修改，只能找state=1的数据，同一个imei可以查询多条，但是状态为1的只能为1条
          nbl: Base64.encode(util.timeFormatDay(new Date()))
        }
      }
      //查询旧模块是否在仓库中
    CommonService.goFindList(oldParam).then(res => {
      //如果旧模块在仓库中
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let resultOld=res.data.data.result[0];
        //拿到主表ID之后查询主表，寻找旧模块所在人员是否是当前登录人
        let userParam={
          className:'imeiWarehouseInFactoryM',
          data:{
            id:resultOld.mId
          }
        }
        CommonService.goFindList(userParam).then(res => {
          //拿到主表id
          //如果当前登陆人ID和旧模块之前拥有者ID相同
          if(res.data.data.result[0].collectUserId===app.globalData.userInfo.id){
            //模块安装状态为2  0未安装  1已安装  2故障被本人换  3故障被他人换 数据条目中有用户ID 状态   4 为 故障持有
            let oldImeiParam={
              className:'imeiWarehouseInFactoryS',
              data:{
                id:resultOld.id,
                state:2
              }
            }
             //更新状态
            CommonService.goSave(oldImeiParam).then(res=>{
            }).catch((error) => {
            })
          }else{//如果当前登陆人ID和旧模块之前拥有者ID不同
            //首先将旧模块的状态变成3
            let oldImeiParam={
              className:'imeiWarehouseInFactoryS',
              data:{
                id:resultOld.id,
                state:3
              }
            }
             //更新状态
            CommonService.goSave(oldImeiParam).then(res=>{
            }).catch((error) => {
            })
            //再将resultOld的数据复制写入
            let newObjResult={
              className:'imeiWarehouseInFactoryS',
              data:{
                imei:resultOld.imei,//物联网编码
                num:1,//数量
              state:4,//模块安装状态为2  0未安装  1已安装  2故障被本人换  3故障被他人换 数据条目中有用户ID 状态   4 为 故障持有
              sId:resultOld.id,//关联下，子表关联子表
              userId:app.globalData.userInfo.id,//操作者ID
              }
            }
            //写入数据
            CommonService.goSave(newObjResult).then(res=>{
            }).catch((error) => {
            })
          }
        })


      }else{
        //如果旧模块不在仓库中
        let newObjResult={
          className:'imeiWarehouseInFactoryS',
          data:{
            imei:imei,//物联网编码
            num:1,//数量
            state:4,//模块安装状态为2  0未安装  1已安装  2故障被本人换  3故障被他人换 数据条目中有用户ID 状态   4 为 故障持有
            userId:app.globalData.userInfo.id,//操作者ID
          }
        }
        //写入数据
        CommonService.goSave(newObjResult).then(res=>{
        }).catch((error) => {
        })
      }
    }).catch((error) => {
    })
    //秦海文添加结束////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	},
	


  //更新物联网仓库的状态
  updateIotWarehouse(imei){
    let param = {
      isAuth: false,
      className: 'imeiWarehouseInFactoryS',
      data: {
        imei: imei,
        state:0,//秦海文修改，不管仓库功能怎么修改，只能找state=0的数据，同一个imei可以查询多条，但是状态为0的只能为1条
        selectFields: ['id','imei',"mId"],
        nbl: Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    //查询是否在仓库中
    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        let param2={
          className:'imeiWarehouseInFactoryS',
          data:{
            id: result.id,
            state: 1
          }
        }

        //更新状态
        CommonService.goSave(param2).then(res=>{
        }).catch((error) => {
        })
      }
    })
  },

  //绑定设备后回调
  saveEquipmentTx(param,id){
    CommonService.saveEquipmentTx(param).then(res=>{
        let param={
          equipmentId:id
        }
        // CommonService.mongoToElastic(param).then(res=>{
        // }).catch((error) => {
        // })

    }).catch((error) => {
    })
  },

  //模块是否在仓库中
  isExistWare(imei){
    let param = {
      isAuth: false,
      className: 'imeiWarehouseInFactoryS',
      data: {
        searchAll: true,
        imei: imei,
        selectFields: ['id'],
        nbl: Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param,false).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.count) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //获取电池类型
  getBatteryType(){
    let param = {
      isAuth:false,
      className:'batteryType',
      data:{
        searchAll:true,
        nbl: Base64.encode(util.timeFormatDay(new Date())),
        selectFields:["id","name"],
        sort: {
          id: 1
        }
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //获取电压值
  getVoltageList(){
    let param = {
      isAuth:false,
      className:'batteryMinVolSet',
      data:{
        searchAll:true,
        selectFields:["id", "batteryTypeId", "volts", "minVol", "floats"],
        nbl: Base64.encode(util.timeFormatDay(new Date())),
        sort: {
          id: 1
        },
        batteryTypeId: this.data.editInfo.battery.batteryTypeId
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.volts + 'V',
            id: item.id,
            obj: item
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //同步到es
  mongoToElastic(id, isSyncEsOld, oldImei,projectId){
    let param={
      equipmentId: id,
      isUpdateImei: isSyncEsOld,
      projectId:projectId
    }

    if(isSyncEsOld){
      param.oldImei = oldImei;
    }  

    CommonService.mongoToElastic(param).then(res=>{
    }).catch((error) => {
    })
  },

  //查询项目名称（厂家从订单绑设备时查询项目名称，存入searchKey）
	getProjectName(id) {
		let param = {
			isAuth: false,
			className: 'depart',
			data: {
				id: id,
				selectFields: ['id', 'name'],
				nbl: Base64.encode(util.timeFormatDay(new Date()))
			}
		}

		CommonService.goFindList(param).then(res => {
			if (res.data.data && res.data.data.result && res.data.data.result.length) {
				let result = res.data.data.result[0];
				this.setData({
					projectName: result.name
				})
			}
		}).catch((error) => {})
	},

	//2024-9-6更换下来的旧模块归属仓库问题
	updateOldImeiState(type,imei,oldImei,mpName){
		let param={
			type: type,
			newImei: imei,
			memberProjectName: mpName
		}

		if(oldImei){
			param.oldImei = oldImei;
		}

		CommonService.updateOldImeiState(param).then(res => {
		}).catch((error) => {})
	},

  /**
   * 生命周期函数--监听页面初次渲染完成
   *
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
